# -----------------------------------------------
# Author: yuz
# Copyright: 湖南零檬信息技术有限公司
# Email: wagyu2016@163.com
# Phone&Wechat: 18173179913
# Site: http://www.lemonban.com
# Forum: http://testingpai.com
# -----------------------------------------------
import base64
import json
import uuid

import requests
from faker import Faker

from common.logger import log
from config import Config


def get_img():
    """获取验证码"""
    url = Config.HOST + '/captcha.jpg'
    uid = str(uuid.uuid4())
    resp = requests.get(url, params={"uuid": uid})
    return resp.content, uid


def base64_api(uname, pwd, img, typeid):
    """上传图片"""
    base64_data = base64.b64encode(img)
    b64 = base64_data.decode()
    data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""


def adminLogin(username, password, code="lemon"):
    """管理员登录.
    访问登录接口封装成函数
    """
    user = {
        "principal": username,
        "credentials": password,
        "imageCode": code
    }
    response = requests.request(
        'POST',
        # url=Config.urls.adminLogin,
        url="http://mall.lemonban.com:8108/adminLogin",
        json=user
    )
    try:
        content = response.json()
        return content['access_token']
    except Exception as e:
        log.error(f"登录失败:{e}")
        raise e


def upload_image(file, token):
    """图片上传"""
    f = open(file, 'rb')
    headers = {"Authorization": f"Bearer{token}"}
    response = requests.request(
        'POST',
        url="http://mall.lemonban.com:8108/admin/file/upload/img",
        files={"file": f},
        headers=headers
    )
    f.close()
    # 2022/06/c46e4c6e808949528628ca5ecad04661.jpg
    return response.text


def send_sms(mobile):
    """发送验证码"""
    data = {"mobile": mobile}
    response = requests.request(
        'PUT',
        # url=Config.urls.adminLogin,
        url="http://mall.lemonban.com:8107/user/sendRegisterSms",
        json=data
    )
    content = response.text
    return content


def check_sms(mobile, validCode):
    """校验验证码"""
    data = {"mobile": mobile, "validCode": validCode}
    response = requests.request(
        'PUT',
        # url=Config.urls.adminLogin,
        url="http://mall.lemonban.com:8107/user/checkRegisterSms",
        json=data
    )
    content = response.text
    print(content)
    if content == 'The verification code is wrong or expired':
        raise ValueError("验证码错误或者超时")
    return content  # flag


def generate_mobile():
    """生成手机号码"""
    fk = Faker(locale=['zh-CN'])
    mobile = fk.phone_number()
    return mobile


if __name__ == '__main__':
    # send_sms('18111110000')
    c = check_sms('18111110000', '940808')
    print(c)  # aea1907dc00b4a1e96b0b851de8c1599
